<?php

/**
 * ApplicationUser form.
 *
 * @package    project_midnight
 * @subpackage form
 * @author     AlvaroLara
 */
class ApplicationUserForm extends BaseApplicationUserForm
{
  public function configure()
  {
    unset($this['profile_id'],
          $this['idea_user_ranking_list'],
          $this['favourite_list']);

    $this->setWidget('password_check', new sfWidgetFormInput());

    $this->getWidget('password_check')->setOption('type','password');
    $this->getWidget('password')->setOption('type','password');

    $this->setValidator('password_check', new sfValidatorPass());
    $this->setValidator('username', new sfValidatorIgnoreCaseString(array('ignore_case' => true)));

    $this->setValidator('email', new sfValidatorEmail());

    $this->validatorSchema->setPostValidator( new sfValidatorSchemaCompare('password', '==', 'password_check',
        array(),
        array('invalid' => 'The passwords must match')
      ));

    $this->validatorSchema->setPostValidator( new sfValidatorCallback(array('callback' => array($this,'check_username_availability'))));

    $this->getWidgetSchema()->moveField('password_check','after','password');

  }

  public function check_username_availability($validator,$value)
  {
    if(!is_null(ApplicationUserPeer::retrieveByUsername($this->getValue('username'))))
    {
      $message = "Username is already in use. Please select a different one.";
      throw new sfValidatorError($validator,$message);
    }

    return $value;
  }
}
